package com.haixiaoke.saas.common.utils;

import com.github.pagehelper.PageHelper;
import com.haixiaoke.saas.common.core.page.PageDomain;
import com.haixiaoke.saas.common.core.page.TableSupport;
import com.haixiaoke.saas.common.utils.sql.SqlUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 分页工具类
 *
 * @author haixiaoke
 */
public class PageUtils extends PageHelper {
    /**
     * 设置请求分页数据
     */
    public static void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        Boolean reasonable = pageDomain.getReasonable();
        PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
    }


    /**
     * 物理分页
     */
    public static <T> List<T> setPage(List<T> list) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        return subList(list,pageNum,pageSize);
    }


    /**
     * 获取list的部分数据
     */
    public static <T> List<T> subList(List<T> list, int pageNum, int pageSize)  {
        List<T> listSort = new ArrayList<>();
        int size = list.size();
        int pageStart = pageNum == 1 ? 0 : (pageNum - 1) * pageSize;// 截取的开始位置
        int pageEnd = Math.min(size, pageNum * pageSize);// 截取的结束位置
        if (size > pageStart) {
            listSort = list.subList(pageStart, pageEnd);
        }
        return listSort;
    }

    /**
     * 清理分页的线程变量
     */
    public static void clearPage() {
        PageHelper.clearPage();
    }
}
